const store = require("../store/index.js");
const config = require("../config.js")

const unpublishStream = async function(roomId, id) {
	const cid = await getPublishCidById(roomId, id);
	console.log(cid);
	const ret = await axios.delete(
		`${config.srsUrl}/api/v1/clients/${cid}`,
	);
	return ret;
}

const publishStream = async function(options) {
	console.log(121,options)
	const pc = new RTCPeerConnection(null);
	pc.addTransceiver('audio', {
		direction: 'sendonly'
	});
	pc.addTransceiver('video', {
		direction: 'sendonly'
	});
	const stream = await navigator.mediaDevices.getUserMedia({
		audio: options.audio == false ? false : true,
		video: options.video == false ? false : {
			facingMode: options.videoType ?? "environment"
		},
	});
	console.log(stream);
	stream.getTracks().forEach(function(track) {
		pc.addTrack(track);
		if (track.kind === 'audio') {
			if (options.audio === false) {
				track.enabled = false;
			}
		}
		if (track.kind === 'video') {
			if (options.video === false) {
				track.enabled = false;
			}
		}
	});
	let offer = await pc.createOffer();
	await pc.setLocalDescription(offer);
	let session = await new Promise(function(resolve, reject) {
		// @see https://github.com/rtcdn/rtcdn-draft
		let data = {
			api: `${config.srsUrl}/rtc/v1/publish/`,
			tid: options.id,
			streamurl: `webrtc://${config.srsUrl.replaceAll('https://', '')
          .replaceAll('http://', '')}/${options.roomId}/${options.id}`,
			clientip: null,
			sdp: offer.sdp,
		};
		console.log('Generated offer: ', data);

		const xhr = new XMLHttpRequest();
		xhr.onload = function() {
			if (xhr.readyState !== xhr.DONE) return;
			if (xhr.status !== 200) return reject(xhr);
			const data = JSON.parse(xhr.responseText);
			console.log('Got answer: ', data);
			if (data.code === 400) {
				resolve(false);
			}
			return data.code ? reject(xhr) : resolve(data);
		};
		xhr.open('POST', `${config.srsUrl}/rtc/v1/publish/`, true);
		xhr.setRequestHeader('Content-type', 'application/json');
		xhr.send(JSON.stringify(data));
	});
	console.log(session);
	if (session === false) {
		return false;
	}
	await pc.setRemoteDescription(
		new RTCSessionDescription({
			type: 'answer',
			sdp: session.sdp
		}),
	);

	function muteAudio(type) {
		stream.getTracks().forEach(function(track) {
			if (track.kind === 'audio') {
				track.enabled = type ?? false;
			}
		});
	}

	function muteVideo(type) {
		stream.getTracks().forEach(function(track) {
			if (track.kind === 'video') {
				track.enabled = type ?? false;
			}
		});
	}
	async function unpublish() {
		stream.getTracks().forEach(function(track) {
			track.stop();
			stream.removeTrack(track);
		});
		pc.close();
		// const cid = await getPublishCidById(options.roomId, options.id);
		// console.log(cid);
		// const ret = await axios.delete(
		//   `${process.env.srsUrl}/api/v1/clients/${cid}`,
		// );
	}

	const userinfo = uni.getStorageSync("user")

	return {
		id: options.id,
		name: options.name ?? userinfo.name,
		roomId: options.roomId,
		pc,
		stream,
		audio: true,
		video: true,
		user: userinfo,
		muteAudio,
		muteVideo,
		unpublish: unpublish,
	};
}

const publishVideoCall = async function() {
	const user = store.state.user.user;
	const pc = new RTCPeerConnection(null);
	pc.addTransceiver('audio', {
		direction: 'sendonly'
	});
	pc.addTransceiver('video', {
		direction: 'sendonly'
	});
	const stream = await navigator.mediaDevices.getUserMedia({
		audio: true,
		video: true,
	});
	console.log(stream);
	stream.getTracks().forEach(function(track) {
		pc.addTrack(track);
	});
	let offer = await pc.createOffer();
	await pc.setLocalDescription(offer);
	let session = await new Promise(function(resolve, reject) {
		// @see https://github.com/rtcdn/rtcdn-draft
		let data = {
			api: `${config.srsUrl}/rtc/v1/publish/`,
			tid: user['id'],
			streamurl: `webrtc://${config.srsUrl.replaceAll('https://', '')
          .replaceAll('http://', '')}/videoCall/${user['id']}`,
			clientip: null,
			sdp: offer.sdp,
		};
		console.log('Generated offer: ', data);

		const xhr = new XMLHttpRequest();
		xhr.onload = function() {
			if (xhr.readyState !== xhr.DONE) return;
			if (xhr.status !== 200) return reject(xhr);
			const data = JSON.parse(xhr.responseText);
			console.log('Got answer: ', data);
			if (data.code === 400) {
				resolve(false);
			}
			return data.code ? reject(xhr) : resolve(data);
		};
		xhr.open('POST', `${config.srsUrl}/rtc/v1/publish/`, true);
		xhr.setRequestHeader('Content-type', 'application/json');
		xhr.send(JSON.stringify(data));
	});
	console.log(session);
	if (session === false) {
		return false;
	}
	await pc.setRemoteDescription(
		new RTCSessionDescription({
			type: 'answer',
			sdp: session.sdp
		}),
	);

	function muteAudio(type) {
		stream.getTracks().forEach(function(track) {
			if (track.kind === 'audio') {
				track.enabled = type ?? false;
			}
		});
	}

	function muteVideo(type) {
		stream.getTracks().forEach(function(track) {
			if (track.kind === 'video') {
				track.enabled = type ?? false;
			}
		});
	}
	async function unpublish() {
		stream.getTracks().forEach(function(track) {
			track.stop();
			stream.removeTrack(track);
		});
		pc.close();
		// const cid = await getPublishCidById(options.roomId, options.id);
		// console.log(cid);
		// const ret = await axios.delete(
		//   `${process.env.srsUrl}/api/v1/clients/${cid}`,
		// );
	}

	const userinfo = store.state.user.user

	return {
		id: user['id'],
		name: userinfo.name,
		roomId: 'videoCall',
		pc,
		stream,
		audio: true,
		video: true,
		user: userinfo,
		muteAudio,
		muteVideo,
		unpublish: unpublish,
	};
}

const subStream = async function(roomId, id, name, audio, video) {
	const pc = new RTCPeerConnection(null);
	pc.addTransceiver('audio', {
		direction: 'recvonly'
	});
	pc.addTransceiver('video', {
		direction: 'recvonly'
	});
	let offer = await pc.createOffer();
	let stream = new MediaStream();
	pc.ontrack = function(event) {
		console.log(event);
		stream.addTrack(event.track);
	};
	await pc.setLocalDescription(offer);
	let session = await new Promise(function(resolve, reject) {
		// @see https://github.com/rtcdn/rtcdn-draft
		let data = {
			api: `${config.srsUrl}/rtc/v1/play/`,
			tid: id,
			streamurl: `webrtc://${config.srsUrl.replaceAll('https://', '')
          .replaceAll('http://', '')}/${roomId}/${id}`,
			clientip: null,
			sdp: offer.sdp,
		};
		console.log('Generated offer: ', data);

		const xhr = new XMLHttpRequest();
		xhr.onload = function() {
			if (xhr.readyState !== xhr.DONE) return;
			if (xhr.status !== 200) return reject(xhr);
			const data = JSON.parse(xhr.responseText);
			console.log('Got answer: ', data);
			return data.code ? reject(xhr) : resolve(data);
		};
		xhr.open('POST', `${config.srsUrl}/rtc/v1/play/`, true);
		xhr.setRequestHeader('Content-type', 'application/json');
		xhr.send(JSON.stringify(data));
	});
	await pc.setRemoteDescription(
		new RTCSessionDescription({
			type: 'answer',
			sdp: session.sdp
		}),
	);

	function close() {
		stream.getTracks().forEach(function(track) {
			track.stop();
			stream.removeTrack(track);
		});
		pc.close();
	}

	return {
		id,
		roomId,
		pc,
		stream,
		name,
		audio: audio ?? false,
		video: video ?? false,
		close,
	};
}

const subVideoCallStream = async function(id, name) {
	const pc = new RTCPeerConnection(null);
	pc.addTransceiver('audio', {
		direction: 'recvonly'
	});
	pc.addTransceiver('video', {
		direction: 'recvonly'
	});
	let offer = await pc.createOffer();
	let stream = new MediaStream();
	pc.ontrack = function(event) {
		console.log(event);
		stream.addTrack(event.track);
	};
	await pc.setLocalDescription(offer);
	let session = await new Promise(function(resolve, reject) {
		// @see https://github.com/rtcdn/rtcdn-draft
		let data = {
			api: `${config.srsUrl}/rtc/v1/play/`,
			tid: id,
			streamurl: `webrtc://${config.srsUrl.replaceAll('https://', '')
          .replaceAll('http://', '')}/videoCall/${id}`,
			clientip: null,
			sdp: offer.sdp,
		};
		console.log('Generated offer: ', data);

		const xhr = new XMLHttpRequest();
		xhr.onload = function() {
			if (xhr.readyState !== xhr.DONE) return;
			if (xhr.status !== 200) return reject(xhr);
			const data = JSON.parse(xhr.responseText);
			console.log('Got answer: ', data);
			return data.code ? reject(xhr) : resolve(data);
		};
		xhr.open('POST', `${config.srsUrl}/rtc/v1/play/`, true);
		xhr.setRequestHeader('Content-type', 'application/json');
		xhr.send(JSON.stringify(data));
	});
	await pc.setRemoteDescription(
		new RTCSessionDescription({
			type: 'answer',
			sdp: session.sdp
		}),
	);

	function close() {
		stream.getTracks().forEach(function(track) {
			track.stop();
			stream.removeTrack(track);
		});
		pc.close();
	}

	return {
		id,
		pc,
		stream,
		name,
		audio: true,
		video: true,
		close,
	};
}

export default {
	subStream,
	subVideoCallStream,
	publishVideoCall,
	publishStream,
	unpublishStream
}